package leetcode.f1t100;

import java.util.ArrayList;
import java.util.List;

/**
 * 给n, k, n代表数组长度, 输出n的数组字典序第k个值
 * https://leetcode.com/problems/permutation-sequence/
 *
 * @Author lichongxiao
 * @Date 2022/10/25 14:41
 */
public class Q60_PermutationSequence {
    public String getPermutation(int n, int k) {
        List<Integer> nums = new ArrayList<>();
        int[] step = new int[n+1];
        nums.add(1);
        step[1] = 1;
        for (int i = 2; i <= n; i++) {
            step[i] = step[i-1] * i;
            nums.add(i);
        }
        return process(n, k-1, step, nums);
    }

    private String process(int n, int k, int[] step,List<Integer> nums) {
        if(n == 1){
            return nums.get(0).toString();
        }
        int cur = k / (step[n-1]);
        String s = nums.get(cur).toString();
        nums.remove(cur);
        return s + process(n-1,k%step[n-1],step,nums);
    }


    public static void main(String[] args) {
        System.out.println(new Q60_PermutationSequence().getPermutation(4, 23));
    }
}
